package com.abe.signature;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;
import com.yanzhenjie.permission.runtime.PermissionRequest;

public class PermissionUtils {

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static PermissionRequest createRequest(final Context context,
                                                  Action action, final String... permissions) {
        return AndPermission.with(context).runtime().permission(permissions)
                .onGranted(action)
                .onDenied(createDeniedAction(context, permissions))
                .rationale(createRationale());
    }

    private static Rationale<List<String>> createRationale() {
        return new Rationale<List<String>>() {
            @Override
            public void showRationale(Context context,
                                      List<String> permissions, RequestExecutor executor) {
                // 这里使用一个Dialog询问用户是否继续授权。
                // 如果用户继续：
                executor.execute();
                // 如果用户中断：
                executor.cancel();
            }

        };
    }

    private static Action<List<String>> createDeniedAction(
            final Context context, final String... permissions) {
        return new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                if (AndPermission.hasAlwaysDeniedPermission(context,
                        permissions)) {
                    // // 这里使用一个Dialog展示没有这些权限应用程序无法继续运行，询问用户是否去设置中授权。
                    // AndPermission.with(context).runtime().setting()
                    // .onComeback(new Setting.Action() {
                    // @Override
                    // public void onAction() {
                    // // 用户从设置回来了。
                    // }
                    // }).start();
                    permissionFail(context, data);
                }
            }
        };
    }

    // 动态权限
    private static void permissionFail(final Context context, List<String> data) {
        if (data == null)
            return;
        List<String> ppData = checkPermissions(data);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < ppData.size(); i++) {
            builder.append(ppData.get(i)).append("\n");
        }
        builder.append("您拒绝了我们以上必要的一些权限，请在设置中授权！");
        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("提示").setIcon(R.mipmap.ic_launcher)
                .setMessage(builder.toString())
                .setNegativeButton("取消", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // NormalUtils.getAppDetailSettingIntent(context);
                        // 这里使用一个Dialog展示没有这些权限应用程序无法继续运行，询问用户是否去设置中授权。
                        AndPermission.with(context).runtime().setting().start();
                    }
                }).create();
        dialog.show();
    }

    private static List<String> checkPermissions(List<String> permissions) {
        List<String> ppList = new ArrayList<>();
        if (permissions == null)
            return ppList;
        String[] ppPermissions = {Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE, Permission.READ_CALENDAR,
                Permission.WRITE_CALENDAR, Permission.CAMERA,
                Permission.READ_CONTACTS, Permission.WRITE_CONTACTS,
                Permission.GET_ACCOUNTS, Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION, Permission.RECORD_AUDIO,
                Permission.READ_PHONE_STATE, Permission.CALL_PHONE,
                Permission.READ_CALL_LOG, Permission.WRITE_CALL_LOG,
                Permission.ADD_VOICEMAIL, Permission.USE_SIP,
                Permission.PROCESS_OUTGOING_CALLS, Permission.BODY_SENSORS,
                Permission.SEND_SMS, Permission.READ_SMS,
                Permission.RECEIVE_SMS, Permission.RECEIVE_WAP_PUSH,
                Permission.RECEIVE_MMS};
        String[] ppNames = {"允许程序写入外部存储", "允许程序读取外部存储", "允许程序读取用户的日程信息",
                "写入日程", "打开相机", "读取联系人", "修改联系人", "访问手机账户", "精确定位", "定位", "录音",
                "读写手机状态", "拨打电话", "读取通话记录", "修改通话记录", "添加语音邮件", "视频服务",
                "允许应用程序监听、控制、取消呼出电话", "传感器", "发短信", "读短信", "接收短信",
                "接收WAP_PUSH", "接收彩信"};
        for (int i = 0; i < permissions.size(); i++) {
            for (int j = 0; j < ppPermissions.length; j++) {
                if (permissions.get(i).equals(ppPermissions[j])) {
                    ppList.add(ppNames[j]);
                }
            }
        }
        return ppList;
    }
}
